%% Prepare N2 Data Set
clear;
close;

[name path] = uigetfile({'*.GTB'});
Head = file_Load(name, path, 'Head');
Data = file_Load(name, path, 'Data');

% Start ~ End Indexes (Stage Time)
Fs      = Head.SampRate;
n_time  = Head.Stage.Duration * Fs;
n_epch  = length(Head.Stage.Time);
stime   = Head.StartDate + Head.StartTime;
sidx    = util_GetOffIndex(stime,Fs,Head.Stage.Time(1));
eidx    = sidx+(n_time * n_epch)-1;
n_chan  = size(Data,1);

Data = reshape(Data(:,sidx:eidx), [n_chan n_time n_epch]);

idx = ~isnan(Head.Stage.Series(:,3));
N2 = Data(:,:,idx);
n_n2 = size(N2,3);

Data = reshape(N2, [n_chan n_time*n_n2]);
Head.TimeNum = size(Data,2);
Head.Stage.Label = {'N2'};
Head.Stage.Color = {'R'};
Head.Stage.Series = Head.Stage.Series(idx);
Head.Stage.Time = Head.Stage.Time(idx);

Head.FileName = 'N2.gtb';
file_Save(Head,Data,[],[]);

%% Load
clear;
close;

[name path] = uigetfile({'*.GTB'});
handles.Head = file_Load(name, path, 'Head');
handles.n_file = 1;
handles.i_file = 1;
handles.mode = 'file';

[Event ok] = psg_DetectSpindle(handles);

%%
clear;
close;

[name path] = uigetfile({'*.GTB'});
Head = file_Load(name, path, 'Head');
Data = file_Load(name, path, 'Data');
Data = util_DataReference(Data, Head.RefeChan);

fs = Head.SampRate;
Wn = [10 16];
win = 'hann';
mul = 5;

for c = 1 : Head.ChanNum
    [Data(c,:) b] = FirFilter(Data(c,:),fs,Wn,win,mul);
end

Fig_ScrollData(Head, Data);